import { useWebSocket, UseWebSocketReturn } from "@vueuse/core";
import { onUnmounted, ref } from "vue";

let client: UseWebSocketReturn<any>;
const cardReaderStatus = ref({
  status: -1,
  message: "硬件未连接",
});
let readCardCallbackSuccess: Array<Function> = [];
const connectSocket = () => {
  client = useWebSocket("ws://127.0.0.1:18890", {
    autoReconnect: true,
    heartbeat: true,
  });
  client.ws.value?.addEventListener("open", (data) => {
    console.log("open", data);
    cardReaderStatus.value = {
      status: 1,
      message: "接口打开成功",
    };
    const result = client.send(
      JSON.stringify({
        name: "openPush",
        withImg: false,
        interval: "1000",
      })
    );
    if (result) {
      cardReaderStatus.value = {
        status: 1,
        message: "准备就绪，请扫码",
      };
    }
  });
  client.ws.value?.addEventListener("error", (err) => {
    console.log("error", err);
  });
  client.ws.value?.addEventListener("close", (data) => {
    console.log("close", data);
    client.open();
  });
  client.ws.value?.addEventListener("message", (data) => {
    // console.log("message", JSON.parse(data.data));
  });
};

export const useWs = (callback) => {
  // console.log(readCardCallbackSuccess);
  readCardCallbackSuccess.unshift(callback);
  if (!client) {
    connectSocket();
  }
  const callbackFun = (data) => {
    console.log("message1", JSON.parse(data.data));
    const resultData: any = JSON.parse(data.data);

    if (resultData.name !== "openPush" && resultData.name !== "") {
      cardReaderStatus.value = {
        status: resultData.resultFlag,
        message: resultData.errorMsg,
      };
      if (readCardCallbackSuccess[0] === callback) {
        callback(resultData);
      }
    } else {
    }
  };
  client.ws.value?.addEventListener("message", callbackFun);
  onUnmounted(() => {
    client.ws.value?.removeEventListener("message", callbackFun);
    const index = readCardCallbackSuccess.findIndex(
      (item) => item === callback
    );
    if (index !== -1) {
      readCardCallbackSuccess.splice(index, 1);
    }
  });
  return {
    cardReaderStatus,
  };
};

export default connectSocket;
